import { openPage } from '@/utils/tabs'

export default {
    namespaced: true,
    state:()=>({
        tabs: [],
        activeValue: '/home'
    }),
    getters: {
        getTabs(state) {
            return state.tabs;
        },
        getActiveValue(state) {
            return state.activeValue;
        },
        getActiveIndex(state) {
            let index = state.tabs.findIndex(e => e.path == state.activeValue);
            return index;
        }
    },
    mutations: {
        addTabs(state, val) {
            state.tabs.push(val);
        },
        removePage(state, index) {
            state.tabs.splice(index, 1);
        },
        removeAllPage(state) {
            state.tabs.splice(1, state.tabs.length - 1);
            let newTab = state.tabs[0];
            if(newTab) {
                state.activeValue = newTab.path;
                openPage(newTab.path);
            }
        },
        removeOtherPage(state) {
            let index = state.tabs.findIndex(e => e.path == state.activeValue);
            //删除前半截[0-index-1]
            if(index - 1 > 0) {
                state.tabs.splice(1, index - 1);
            }
            //在把后半截删掉
            state.tabs.splice(2, state.tabs.length);
        },
        setActiveValue(state, value) {
            state.activeValue = value;
        }
    },
    actions: {
        initTab({ commit, state }, menu){
            if(state.tabs.length <= 0) {
                commit("setActiveValue", menu.path);
                commit("addTabs", menu);
            }
        },
        openPage({ commit, state }, menu) {
            let tabs = state.tabs;
            commit("setActiveValue", menu.path);
            for(let i = 0; i < tabs.length; i ++) {
                if(tabs[i].path === menu.path) {
                    return;
                }
            }
            commit("addTabs", menu);
        },
        removePage({ commit, state }, path) {
            let tabs = state.tabs;
            for(let i = 0; i < tabs.length; i ++) {
                if(state.activeValue == path) {
                    let newTab = tabs[i + 1] || tabs[i - 1];
                    if(newTab) {
                        state.activeValue = newTab.path;
                        openPage(newTab.path);
                    }
                }
                if(tabs[i].path === path) {
                    commit("removePage", i);
                    return;
                }
            }
        },
        removeCurrentPage({ dispatch, state }) {
            let index = state.tabs.findIndex(e => e.path == state.activeValue);
            if(index > 0) {
                dispatch('removePage', state.activeValue)
            }
        },
        removeOtherPage({ commit }) {
            commit("removeOtherPage");
        },
        removeAllPage({ commit }) {
            commit("removeAllPage");
        }
    },
}